package com.example.everying.utils;

import okhttp3.*;
import java.io.IOException;
import java.util.Objects;
/**
 * @program: everything
 * @description:
 * @author: zw
 * @create: 2025-07-15 11:06
 **/

public class IdCardValidator {
    private final OkHttpClient client;
    private final String apiUrl;
    private final String appCode;

    // 通过构造函数注入配置
    public IdCardValidator(String apiUrl, String appCode) {
        this.apiUrl = apiUrl;
        this.appCode = appCode;
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .build();
    }

    /**
     * 验证身份证信息
     * @param name 姓名
     * @param idNo 身份证号码
     * @return 验证结果JSON字符串
     * @throws IOException 网络异常
     * @throws AuthenticationException 认证失败
     * @throws ServiceException 服务异常
     */
    public String validate(String name, String idNo) throws IOException, AuthenticationException, ServiceException {
        // 检查输入参数
        if (name == null || name.trim().isEmpty() || idNo == null || idNo.trim().isEmpty()) {
            throw new IllegalArgumentException("姓名和身份证号不能为空");
        }

        // 构建请求体
        RequestBody formBody = new FormBody.Builder()
                .add("name", name)
                .add("idNo", idNo)
                .build();

        // 构建请求
        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("Authorization", "APPCODE " + appCode)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .post(formBody)
                .build();

        // 执行请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return Objects.requireNonNull(response.body()).string();
            } else {
                String errorBody = response.body() != null ? response.body().string() : "无错误详情";
                handleErrorResponse(response.code(), errorBody);
                return null; // 不会执行到这里，因为handleErrorResponse会抛出异常
            }
        }
    }

    /**
     * 处理错误响应
     */
    private void handleErrorResponse(int statusCode, String errorBody) throws AuthenticationException, ServiceException {
        switch (statusCode) {
            case 400:
                throw new IllegalArgumentException("请求参数错误: " + errorBody);
            case 401:
                throw new AuthenticationException("认证失败，AppCode无效: " + errorBody);
            case 403:
                throw new ServiceException("访问被拒绝，可能是套餐包用尽: " + errorBody);
            case 404:
                throw new ServiceException("API不存在: " + errorBody);
            case 500:
                throw new ServiceException("网络错误: " + errorBody);
            default:
                throw new ServiceException("未知错误，状态码: " + statusCode + ", 详情: " + errorBody);
        }
    }

    // 自定义异常类
    public static class AuthenticationException extends Exception {
        public AuthenticationException(String message) {
            super(message);
        }
    }

    public static class ServiceException extends Exception {
        public ServiceException(String message) {
            super(message);
        }
    }
    public static void main(String[] args) {
        // 从配置文件或环境变量读取配置
        String apiUrl = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
        String appCode = "75ea290d3be34c5d8b6469aeede82aa2"; // 实际使用时应从安全配置中读取

        // 创建验证器实例
        IdCardValidator validator = new IdCardValidator(apiUrl, appCode);

        try {
            // 示例验证
            String result = validator.validate("孙泽扬", "130184200104301018");
            System.out.println("验证结果: " + result);
        } catch (IdCardValidator.AuthenticationException e) {
            System.err.println("认证错误: " + e.getMessage());
            System.err.println("请检查AppCode是否正确或有效");
        } catch (IllegalArgumentException e) {
            System.err.println("参数错误: " + e.getMessage());
        } catch (IdCardValidator.ServiceException e) {
            System.err.println("服务错误: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("网络错误: " + e.getMessage());
            System.err.println("请检查网络连接或API端点是否正确");
        } catch (Exception e) {
            System.err.println("未知错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
